from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from openai import OpenAI
import requests,random
import re,os,hashlib
import edge_tts
app = FastAPI()
app.mount("/cdn",StaticFiles(directory="cdn"), name="cdn")
client = OpenAI(
    # This is the default and can be omitted
    api_key='sk-b1esUpD072rw3V46C2C242EfFa1b4967B30952Df6c87D378',
    base_url = 'http://s.yzwwxm.top:9010/v1'
)
html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
            var text=""
            var ws = new WebSocket("ws://localhost:8000/ws");
            ws.onmessage = function(event) {
                var messages = document.getElementById('messages')
                var message = document.createElement('li')
                var content = document.createTextNode(event.data)
                text+=event.data
                messages.textContent = text
            };
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""

@app.get("/")
async def get():
    return HTMLResponse(html)

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        print(data)
        txt=""
        stream=client.chat.completions.create(
        messages=[
            {
                "role":"system",
                "content":"你是一个智能助手，回答问题时使用易于朗读的文本，尽量和真人的语气接近"
            },
            {
                "role": "user",
                "content":data,
            }
        ],
        model="deepseek-chat",
        stream=True
    )
        print(stream)
        for message in stream:
            print(message)
            for chunk in stream:
                # print(chunk)
                pattern = r'.*[.?!。！？]$'
                reason=chunk.choices[0].finish_reason
                txt+=chunk.choices[0].delta.content or ""   
                if (re.match(pattern,txt)) and not reason=="stop":        
                    try:
                        print(txt)
                        url=await tts(txt.strip())
                        await websocket.send_text(url)
                        txt=""
                    except:
                        print("error")
                        pass
async def tts(text):
    voice="zh-CN-XiaoxiaoNeural"
    rate="+0%"
    pitch="+0%"
    md5=hashlib.md5((text+voice+rate+pitch).encode('utf-8')).hexdigest()
    output=os.path.join(os.path.dirname(__file__),"cdn",md5+".mp3")
    if not os.path.exists(output):
        communicate=edge_tts.Communicate(text,voice=voice,rate=rate)
        await communicate.save(output)
        return "http://localhost:8000/cdn/"+md5+".mp3"
    
# async def openai_streaming_chat(websocket: WebSocket, prompt: str):
#     response=client.chat.completions.create(
#     messages=[
#         {
#             "role": "user",
#             "content":prompt,
#         }
#     ],
#     model="deepseek-chat",
#     stream=True
# )
#     for message in response:
#         if 'choices' in message:
#             print(message['choices'][0]['delta']['content'] or " ")
#             await websocket.send_text(message['choices'][0]['delta']['content'])
# def tts(text):
#     url = "https://www.text-to-speech.cn/getSpeek.php"

#     payload = {
#         "user_id": str(random.randint(120100,2000000)),
#         "language": "中文（普通话，简体）",
#         "voice": "zh-CN-XiaoxiaoMultilingualNeural",
#         "text": text,
#         "role": "0",
#         "style": "0",
#         "styledegree": "1",
#         "volume": "75",
#         "predict": 1,
#         "rate": 0,
#         "pitch": 0,
#         "kbitrate": "audio-16khz-128kbitrate-mono-mp3",
#         "silence": "",
#         "yzm": "^\""
#     }
#     headers = {
#         "Referer": "https://www.text-to-speech.cn/",
#         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",
#         "accept": "*/*",
#         "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
#         "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
#         "origin": "https://www.text-to-speech.cn",
#         "referer": "https://www.text-to-speech.cn/"
#     }

#     response = requests.post(url, data=payload, headers=headers)
#     url=response.json()['download']
#     return url
    # print(response.json())
    # mp3=requests.get(url)
    # with open(path, "wb") as f:
    #     f.write(mp3.content)